Pandas dataframe with MultiIndex: check if string is contained in index level

35

import numpy as np
import pandas as pd

arrays = [np.array(['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux']),
          np.array(['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'])]

df = pd.DataFrame(np.random.randn(8, 4), index=arrays)


#You can apply mask like this
df = df.iloc[df.index.get_level_values(1).str.contains('ne')]
#OR
df = df.iloc[(df.index.get_level_values(0).str.contains('ba')) | (df.index.get_level_values(1).str.contains('ne'))]

Comments

Submit
0 Comments